package cn.edu.seu.herald.informationplatform.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.VoteItem;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.VoteDataAccess;
import cn.edu.seu.herald.informationplatform.dao.database.VoteItemDataAccess;

public class VoteItemDelete extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//参数：itemId
		//功能：删除Id为"itemId"的活动，根据链接session获得leagueId

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		try {
			/*String voteIdParam = request.getParameter("voteId");
			if (voteIdParam == null) {
				response.getWriter().println("操作失败");
				return;
			}
			int voteId = Integer.valueOf(voteIdParam);
			
			LeagueUserSessionCookieAccess luSessionCookieAccess =
					new LeagueUserSessionCookieAccess(request);
			int leagueId = luSessionCookieAccess.getLeagueId();
			
			VoteDataAccess vdao = VoteDataAccess.getInstance();
			VoteItemDataAccess vidao =  VoteItemDataAccess.getInstance();
			
			VoteItem item = vidao.getVoteItemById(voteId);
			if (item == null) {
				response.getWriter().println("操作失败");
				return;
			}
			
			if (item.getVote().getLeagueId() != leagueId) {
				response.getWriter().println("操作失败");
				return;
			}
			
			vidao.deleteVoteItemsByVoteId(voteId);*/
			VoteItemDataAccess voteItemDataAccess = VoteItemDataAccess.getInstance();
			int itemId = Integer.parseInt(request.getParameter("itemId"));
			VoteItem voteItem = voteItemDataAccess.getVoteItemById(itemId);
			String path = getServletContext().getRealPath("/");
			String rawRealPath = path+voteItem.getPicture();
			Properties pro = System.getProperties();
	        String osName = pro.getProperty("os.name");
	        File file = null;
	        System.out.println(rawRealPath);
	        if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
	        	file = new File(rawRealPath);  
	        }else{
	        	file = new File(rawRealPath.replaceAll("\\\\", "/"));
	        }
			
			
		    if (file.isFile() && file.exists()) {  
		        file.delete();  
		    }  
			voteItemDataAccess.deleteVoteItemById(itemId);
			LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
			response.sendRedirect("./polling.jsp?league="+luSessionCookieAccess.getLeagueId());
		} catch (Exception e) {
			response.getWriter().println("操作失败");
			return;
		}
	}

	
}
